#encoding: utf-8
class Users::SessionsController < Devise::SessionsController
  def create
    if resp = request.env["rack.openid.response"]
      case resp.status
      when OpenID::Consumer::FAILURE
        puts "很抱歉，我们无法与标识符验证您的身份 '{openid}'."
        redirect_to welcome_index_path
      when OpenID::Consumer::SETUP_NEEDED
        puts "请求失败"
        redirect_to welcome_index_path
      when OpenID::Consumer::CANCEL
        puts "取消登陆"
        redirect_to welcome_index_path
      when OpenID::Consumer::SUCCESS
        # Access additional informations:
        @user = User.find_by_identity_url(params[:user][:identity_url])
        if @user.nil?
          @user = User.new
          @user.email = "#{params[:user][:identity_url].split("/")[3]}@aouth.com"
          @user.password = params[:user][:identity_url]
          @user.identity_url = params[:user][:identity_url]
        @user.save
        end
        user_token = UserOapenidToken.getOpinfo(@user.id, randerToken)
        
        # @user.reset_authentication_token
        # sign_in(@user)
        # respond_with resource, location: after_sign_in_path_for(resource)
        puts "登陆成功"
        redirect_to openid_show_path(:token => user_token)
        
      end
    else
      super
    end
  end

  protected

  def use_openid?(url)
    if url.to_s.strip != ""
    return true
    end
    return false
  end

  def verification_openid(identity_url)
    Rack::OpenID.build_header(:identifier => identity_url)
    # OpenID::Consumer.new

    if resp = request.env["rack.openid.response"]
      case resp.status
      when OpenID::Consumer::FAILURE
        puts "Sorry, we could not authenticate you with the identifier '{openid}'."
        redirect_to "users/sign_in"
      when OpenID::Consumer::SETUP_NEEDED
        puts "Immediate request failed - Setup Needed"
        redirect_to "users/sign_in"
      when OpenID::Consumer::CANCEL
        puts "Login cancelled."
        redirect_to "users/sign_in"
      when OpenID::Consumer::SUCCESS
        # Access additional informations:
        # puts params['openid.sreg.email']
        # puts params['openid.sreg.fullname']

        # Startup something
        puts "Login successfull."
        # Maybe something like
        # session[:user] = User.find_by_openid(oidresp.display_identifier)
        redirect_to :welcome
      end
      redirect_to "users/sign_in"
    end

  end

  def root_url
    request.url.match(/(^.*\/{2}[^\/]*)/)[1]
  end
  
  
  def randerToken
    SecureRandom.base64(32)
  end

end
